﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProjectN.Core.Fore
{
    public interface INamed
    {
        string AsString();
    }
    public partial class PropertyEditForm : Form
    {
        public PropertyEditForm()
        {
            InitializeComponent();
        }

        public void UpdateItems()
        {
            ItemSelector.Items.Clear();
            if (!items.Any())
            {
                ItemSelector.Text = string.Empty;
                ItemSelector.Enabled = false;
                PropertyGrid.SelectedObject = null;
                return;
            }

            ItemSelector.Items.Clear();
            ItemSelector.Items.AddRange([.. Items.Select(item => GetName(item))]);
            ItemSelector.SelectedIndex = 0;
            ItemSelector.Enabled = true;
            UpdateSelectedObject();
        }

        private static string GetName(object obj)
            => (obj as INamed)?.AsString()
            ?? obj.GetType().FullName
            ?? obj.ToString()
            ?? obj.GetType().Name;

        private IEnumerable<object> items = null!;

        private void UpdateSelectedObject()
        {
            if (ItemSelector.SelectedIndex < 0 || ItemSelector.SelectedIndex >= Items.Count())
                return;

            PropertyGrid.SelectedObject = Items.ElementAt(ItemSelector.SelectedIndex);
        }

        private void ItemSelector_SelectedIndexChanged(object? sender, EventArgs @event)
            => UpdateSelectedObject();

        public required IEnumerable<object> Items
        {
            get => items;
            set
            {
                items = value;
                UpdateItems();
            }
        }

        public required string Title
        {
            get => base.Text;
            set => base.Text = value;
        }

        public static void Show(Form? owner, Collection<object> items, string title)
            => new PropertyEditForm { Items = items, Title = title }.Show(owner);
        public static void Show(Form? owner, object item, string title)
            => Show(owner, [item], title);
        public static void Show(Collection<object> items, string title)
            => Show(null, items, title);
        public static void Show(object item, string title)
            => Show(null, [item], title);
    }
}
